package com.cars.elasticsearch.util.elasticSearch;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.cars.elasticsearch.exception.EsException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: caoqianfan
 * @date: 2023/10/12 17:27
 */
@Slf4j
@Component
public class IndexUtil {

    @Resource
    private ElasticsearchClient client;

    /**
     * 判断索引是否不存在.
     *
     * @param indexName index名称
     */
    public boolean existIndex(String indexName) {
        try {
            BooleanResponse booleanResponse = client.indices().exists(e -> e.index(indexName));
            log.info(booleanResponse.toString());
            return booleanResponse.value();
        } catch (IOException e) {
            throw new EsException("在es中检测索引【" + indexName + "】出错，错误信息为：" + e.getMessage());
        }
    }

    /**
     * 创建索引.
     *
     * @param indexName index名称
     */
    public void createIndex(String indexName) {
        try {
            CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index(indexName));
            log.info(createIndexResponse.toString());
        } catch (IOException e) {
            throw new EsException("在es中创建索引【" + indexName + "】出错，错误信息为：" + e.getMessage());
        }
    }

    /**
     * 删除索引.
     *
     * @param indexName index名称
     */
    public void removeIndex(String indexName) {
        try {
            DeleteIndexResponse deleteIndexResponse = client.indices().delete(c -> c.index(indexName));
            System.out.println(deleteIndexResponse.toString());
        } catch (IOException e) {
            throw new EsException("在es中创建索引【" + indexName + "】出错，错误信息为：" + e.getMessage());
        }
    }

}